import requests
from bs4 import BeautifulSoup
from py2neo import Graph, Node, Relationship, NodeMatcher
import re

qut_graph = Graph(
    'http://localhost:7474',
    username='neo4j',
    password='00001011'
)

matcher = NodeMatcher(qut_graph)

qut_node = matcher.match('学校', name='青岛理工大学').first()
school_nodes = matcher.match('学院')
person_nodes = matcher.match('人')


def insert_from_file():
    with open('组织机构.txt') as file:
        line = file.readline()

        org_node = None
        while line:
            filtered = re.sub(r'（.+）|、.+$|\s.*', '', line)
            if len(filtered) > 1:
                if org_node:
                    qut_graph.create(Relationship(qut_node, '组织机构', org_node))
                    print('创建最终关系')

                org_node = Node('组织机构', name=filtered)
                print('创建组织节点')

            alias = re.search(r'（..+）|、.+$', line)
            if alias:
                alias_node = Node('组织机构', name=re.sub(r'[（）、]', '', alias.group()))
                qut_graph.create(Relationship(org_node, '别称', alias_node))
                print('创建别名关系')

            line = file.readline()


def insert_from_website():
    for school in school_nodes:
        if school['name'] == '土木工程学院':
            url = 'http://civil.qut.edu.cn/jgsz/xbzx.htm'
            req = requests.get(url, 'html.parser')
            bs = BeautifulSoup(req.content)
            print(bs)
            break


insert_from_website()
